package com.example.demo.config;

import com.example.demo.constant.HttpStatusCode;
import com.example.demo.exception.RateLimiterException;
import com.google.common.util.concurrent.RateLimiter;
import org.apache.http.client.HttpResponseException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname AppInterceptor
 * @description
 * @date 2024/03/20 21:24
 * <p>
 * ******************************************************
 */
@Component
public class AppInterceptor implements HandlerInterceptor {


    private final int timeout = 1000;
    private final int time = 50;
    private final RateLimiter limiter = RateLimiter.create(time);
    private final AtomicInteger REQ_TIMES = new AtomicInteger(0);


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("请求总次数：" + REQ_TIMES.incrementAndGet());
        if (!limiter.tryAcquire(timeout, TimeUnit.MILLISECONDS)) {
            // http请求成功，内部状态错误
            throw new RateLimiterException("达到流控上限，请稍后重试!");
            // http 请求错误
//            response.setStatus(HttpStatus.FORBIDDEN.value()); // 设置状态码为 403
//            response.getWriter().write("达到流控上限，请稍后重试!"); // 设置响应内容
//            return false;
        }
        return true;
    }

    /**
     * 比较当前时间是否在范围内,
     *
     * @param instance
     * @param startTime
     * @param endTime
     * @return
     */
    public boolean comparator(Calendar instance, String startTime, String endTime) {
        String hour = instance.get(Calendar.HOUR_OF_DAY) > 9 ? String.valueOf(instance.get(Calendar.HOUR_OF_DAY)) : "0" + instance.get(Calendar.HOUR_OF_DAY);
        String minute = instance.get(Calendar.MINUTE) > 9 ? String.valueOf(instance.get(Calendar.MINUTE)) : "0" + instance.get(Calendar.MINUTE);
        if (startTime.compareTo(hour + ":" + minute) <= 0 && endTime.compareTo(hour + ":" + minute) >= 0) {
            return true;
        }
        return false;
    }
}
